package cn.sll.user.service.impl;

import cn.sll.base.cons.PhoneRegisterCons;
import cn.sll.base.cons.WechatCons;
import cn.sll.base.jwt.JwtUtils;
import cn.sll.base.jwt.RsaUtils;
import cn.sll.base.jwt.UserInfo;
import cn.sll.base.util.AjaxResult;
import cn.sll.base.util.BussinessException;
import cn.sll.base.util.HttpUtil;
import cn.sll.base.util.MD5Utils;
import cn.sll.system.domain.Menu;
import cn.sll.system.mapper.MenuMapper;
import cn.sll.system.mapper.PermissionMapper;
import cn.sll.user.domain.Logininfo;
import cn.sll.user.domain.User;
import cn.sll.user.domain.Wxuser;
import cn.sll.user.dto.AccountDto;
import cn.sll.user.dto.BinderDto;
import cn.sll.user.dto.WecathDto;
import cn.sll.user.mapper.LogininfoMapper;
import cn.sll.user.mapper.UserMapper;
import cn.sll.user.service.IWxuserService;
import cn.sll.user.service.LoginService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IWxuserService wxuserService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Value("${jwt.pri}")
    private String jwtPri;


    @Override
    public HashMap<String, Object> account(AccountDto dto) {

        // 参数校验
        //判断用户是否存在
        Logininfo logininfo = logininfoMapper.findByName(dto);
        if (logininfo == null) {
            throw new BussinessException("账号密码有误1");
        }
        //判断密码是否正确
        String password = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        if (!password.equals(logininfo.getPassword())) {
            throw new BussinessException("账号密码有误2");
        }
//        //将token作为key 用户信息作为value存到redis
//        //通过uuid生成token作为key存到redis设置有效时间30
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //重置用户敏感信息
//        logininfo.setPhone("");
//        logininfo.setPassword("");
//        logininfo.setSalt("");
//        log.info("{}", logininfo);
//        // 返回给前端
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo", logininfo);
        HashMap<String, Object> map = getMap(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechat(WecathDto dto) {
        //参数校验
        //通过code调用第二个接口获取token和openid
        String JsonStr = HttpUtil.httpGet(String.format(WechatCons.SECOND_INTER,WechatCons.APPID,WechatCons.SECRET,dto.getCode()));
        //将字符串JSON转换为JSON对象，获取到access_token&openid
        JSONObject jsonObject = JSONObject.parseObject(JsonStr);
        //获取token和openid
        String accessToken = jsonObject.getString("access_token");
        String openId =  jsonObject.getString("openid");
        //通过openid查询是否存在
        Wxuser wxuser = wxuserService.findByOpenId(openId);
        //不存在就跳转到绑定页面 传参数openid，token到前端 "?accessToken="+accessToken+"&openId="+openId;
        if (null== wxuser || null==wxuser.getId()) {
            StringBuffer sb = new StringBuffer()
                    .append("?accessToken=")
                    .append(accessToken)
                    .append("&openId=")
                    .append(openId);
            return AjaxResult.me().fail("nobinder").setResultObj(sb.toString());
        }
        //存在就登陆成功
        Logininfo  logininfo =  logininfoMapper.findByUserId(wxuser.getUserId());
        //将token作为key 用户信息作为value存到redis
        Map<String, Object> map = getMap(logininfo);
        return AjaxResult.me().success(map);
    }

    @Override
    public AjaxResult binder(BinderDto dto) {
        // 参数校验
        // 判断手机验证码是否正确
        String redisSmsCode = (String) redisTemplate.opsForValue().get(String.format(PhoneRegisterCons.BINDER_KEY, dto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode) || !redisSmsCode.equals(dto.getVerifyCode())) {
            throw new BussinessException("验证码错误");
        }
        // 调用第三个接口
        String jsonStr = HttpUtil.httpGet(String.format(WechatCons.THIRD_INTER, dto.getAccessToken(), dto.getOpenId()));
        // 将jsonStr转成实体
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
        // 判断user是否有数据
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null == user) {
            // 没有数据 保存三张表 loininfo user wxuser
            // 实例化user 实例化logininfo
            user = dto.getUser();
            BeanUtils.copyProperties(user, logininfo);
            logininfo.setType(1);
            logininfo.setDisable(true);
            // 先去添加logininfo对象
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        // 添加wxuser
        wxuser.setUserId(user.getId());
        wxuserService.add(wxuser);

        // 登录成功 返回给前端 token和logininfo
        //将token作为key 用户信息作为value存到redis
        Map<String, Object> map = getMap(logininfo);
        return AjaxResult.me().success(map);
    }

    private HashMap<String, Object> getMap(Logininfo logininfo) {
        HashMap<String, Object> result = new HashMap<>();
        // 生成uuid作为redis的key 也就是token
//        String token = UUID.randomUUID().toString();
        // 将token 和logininfo数据保存到redis key：token value：logininfo
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 1.创建UserInfo对象，存储logininfo对象，并用于后续赋值
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);
        // 2.判断是后台用户登录才需要设置菜单信息、权限信息，类型为0那么就是后台用户登录
        if (logininfo.getType() == 0){
            List<String> permissionSn = permissionMapper.findByLoginInfoId(logininfo.getId());
            userInfo.setPermissionSn(permissionSn);
            List<Menu> menus = menuMapper.findMenusBuLoginInfoId(logininfo.getId());
            userInfo.setMenus(menus);
            result.put("permissions",permissionSn );
            result.put("menus", menus);
        }
        // 3.根据密钥文件名称获取到密钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtPri).getFile());
        // 4.根据密钥、用户信息、获取JWT加密串
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo,privateKey,3000);
        // 将用户的敏感信息 清空
        logininfo.setPassword(null);
        logininfo.setPhone(null);
        // 将token和logininfo 返回给前端
        result.put("token", token);
        result.put("logininfo", logininfo);
        return result;
    }
}
